package com.zhn;

//给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点，返回 null 。
//
//题目数据 保证 整个链式结构中不存在环。

public class GetIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode hA = headA;
        ListNode hB = headB;
        int count1 = 0;
        int count2 = 0;
        while (hA != null) {
            count1++;
            hA = hA.next;
        }
        while (hB != null) {
            count2++;
            hB = hB.next;
        }
        hA = headA;
        hB = headB;
        if(count1 < count2){
            ListNode temp = hB;
            hB = hA;
            hA = temp;
            int t = count2;
            count2 = count1;
            count1 = t;
        }
        int len = count1 - count2;

        while(len-- > 0){
            hA = hA.next;
        }
        while(hA != null){
            if(hA == hB)
                return hA;
            hA = hA.next;
            hB = hB.next;
        }
        return null;
    }
}
